const dayjs = require('dayjs');
const {
    getCache,
    updateSectorCache,
    updateRegionCache,
    updateConceptCache,
    updateRoeCache,
    updateRatioCache
} = require('../controllers/cachedController');
const { getStockInfoByCode } = require('../controllers/stockController');

const lowPriceMap = require('../config/lowPriceMap');


let cacheLength = 0;
async function getSectorRegionConceptInfo() {
    if (dayjs().minute() === 6) {
        cacheLength = 0;
    }

    let stocks = getCache();
    let stockCodes = [];
    if (stocks.length > 0) {
        stockCodes = stocks.map((item) => item.code);
    } else {
        stockCodes = Object.keys(lowPriceMap);
    }
    const resList = await getStockInfoByCode(stockCodes);

    console.log(`获取股票板块、地区、概念、净资产收益率、资产负债率信息数量为：${resList.length}，缓存长度：${cacheLength}`);

    if (resList.length > 0 && resList.length > cacheLength) {
        let sectorInfo = {};
        let regionInfo = {};
        let conceptInfo = {};
        let roeInfo = {};
        let assetRatioInfo = {};
        for (i = 0; i < resList.length; i++) {
            let item = resList[i];
            sectorInfo[item.code] = item.sector;
            regionInfo[item.code] = item.region;
            conceptInfo[item.code] = item.concept;
            roeInfo[item.code] = item.roe;
            assetRatioInfo[item.code] = item.assetRatio;
        }
        cacheLength = resList.length;
        updateSectorCache(sectorInfo);
        updateRegionCache(regionInfo);
        updateConceptCache(conceptInfo);
        updateRoeCache(roeInfo);
        updateRatioCache(assetRatioInfo);
    }
}

module.exports = { getSectorRegionConceptInfo };
